package com.srt.util.exception;

import com.srt.context.ApplicationContextHelper;

/**
 * PBusinessException处理工厂
 *
 * @author rd07
 */
public class PExceptionFactory {

    private static ExceptionDefinitions exceptionDefinitions;

    /**
     * 获取错误消息内容
     *
     * @param errorCode
     * @param args
     * @return
     */
    public static String getMessage(String errorCode, String... args) {
        String exceptionPattern = getExceptionDefinitions().getExceptionMessage(errorCode);

        if (args.length > 0) {
            return String.format(exceptionPattern, args);
        }
        return exceptionPattern;
    }

    /**
     * 创建异常
     *
     * @param errorCode
     * @param args
     * @return
     */
    public static PBusinessException create(String errorCode, String... args) {
        String exceptionPattern = getExceptionDefinitions().getExceptionMessage(errorCode);

        if (args.length > 0) {
            String errorMsg = String.format(exceptionPattern, args);
            return new PBusinessException(errorCode, errorMsg);
        }
        return new PBusinessException(errorCode, exceptionPattern);
    }

    private static ExceptionDefinitions getExceptionDefinitions() {
        if (exceptionDefinitions == null) {
            exceptionDefinitions = ApplicationContextHelper.getContext().getBean(ExceptionDefinitions.class);
        }
        return exceptionDefinitions;
    }
}
